let isRefreshing = true;
let subscribers = [];
import { config } from "./config";

const baseUrl = config().apiUrl;
//const baseUrl =  "http://192.168.0.139:8081";

var version = config().version;
var appCode = config().appCode

function onAccessTokenFetched() {
    subscribers.forEach((callback) => {
        callback();
    })
    subscribers = [];
}

function addSubscriber(callback) {
    subscribers.push(callback)
}

function request({ url, data = {}, method, header, callback = '', fail = null } = {}) {
    let _this = this;
    return new Promise((resolve, reject) => {

        let token = wx.getStorageSync("token");
        let openid =  wx.getStorageSync("openid");
        // let pid =  wx.getStorageSync("pid")||'0';
        // let fid =  wx.getStorageSync("fid")||'0';

        if(openid){

            let default_header = {
                "content-type":"application/json",
                appCode: appCode,
                version: version,
                openid: openid,
                // pid: pid,
                // fid: fid
            }
    
            let request_header = Object.assign(default_header , header)
            wx.request({
                url:baseUrl + url,
                data,
                method,
                header: request_header,
                callback,
                fail(res) {
                    reject(res)
                },
                complete: res => {

                    // console.log( callback && res.data.data !== undefined )

                    // console.log( res.statusCode )
                    
                    if ( callback && res.data.data !== undefined ) return callback(res.data.data);
                    let statusCode = res.statusCode;
    
                    if (statusCode == 404) {
                        wx.showModal({ content: '接口不存在', showCancel: false })
                    }
                    else if (statusCode == 200) {

                        if(res.data.code == 200 ){
                            resolve(res.data.data)
                        }
                        else if(res.data.code == 2){
                            addSubscriber(() => {
                                request({ url, data, method, header, callback: resolve })
                            })
        
                            if (isRefreshing) {
                                getNewToken(url, data).then(() => {
                                    onAccessTokenFetched();
                                    isRefreshing = true;
                                })
                            }
                            isRefreshing = false;
                        }
                        else if(res.data.code == 401 || res.data.code == 402){
                            
                            wx.showModal({ 
                                content: res.data.msg, 
                                showCancel: false 
                            })
                            .then((res)=>{
                                if(res.confirm){

                                    wx.removeStorageSync("openid");
                                    wx.removeStorageSync("session_key");
                                    
                                    wx.navigateTo({
                                        url: '/pages/login/login'
                                    });
                                }
                            })

                            wx.hideLoading();
                            
                        }
                        else{
                            
                            if(fail && typeof fail=="function" ){
                                fail(res.data)
                            }
                            else{
                                wx.showModal({ content: res.data.msg, showCancel: false });
                            }
                            wx.hideLoading();
                            
                        }
                    } else {
                        wx.showModal({ content: '服务器报错，请重试！', showCancel: false });
                        wx.hideLoading();
                    }
                }
            })
        }
        else{
            getNewToken(url, data).then(() => {
                request({ url, data, method, header, callback:resolve})
            })
        }
    })
}

function upload({ url, filePath, name, formData, callback = '' } = {}) {
    let _this = this;
    return new Promise((resolve, reject) => {

        wx.uploadFile({
            url:baseUrl + url,
            filePath,
            name,
            formData,
            header: { 
                "openid": wx.getStorageSync("openid"),
                'appCode': appCode,
                'version': version,
                'pid':wx.getStorageSync("pid")||'0',
                'fid':wx.getStorageSync("fid")||'0',
                "content-type": "multipart/form-data"
            },
            callback,
            fail(res) {
                reject(res)
            },
            complete: res => {

                let result = null;

                if(!res.data){
                    return;
                }

                result = JSON.parse(res.data);

                if (callback && callback !== undefined) return callback(result.data);
                let statusCode = res.statusCode;

                if (statusCode == 404) {
                    wx.showModal({ content: '接口不存在', showCancel: false })
                }
                else if (statusCode == 200) {

                    if(result.code === 200){
                        resolve(result.data)
                    }
                    else if(result.code == 200){
                        addSubscriber(() => {
                            upload({ url, filePath, name, formData, callback: resolve })
                        })
    
                        if (isRefreshing) {
                            getNewToken(url).then(() => {
                                onAccessTokenFetched();
                                isRefreshing = true;
                            })
                        }
                        isRefreshing = false;
                    }
                    else if(res.data.code == 401 || res.data.code == 402){
                            
                        wx.showModal({ 
                            content: res.data.msg, 
                            showCancel: false 
                        })
                        .then((res)=>{
                            if(res.confirm){

                                wx.removeStorageSync("openid");
                                wx.removeStorageSync("session_key");
                                
                                wx.navigateTo({
                                    url: '/pages/login/login'
                                });
                            }
                        })

                        wx.hideLoading();
                        
                    }
                    else{
                        wx.hideLoading();
                        wx.showModal({ content: result.message, showCancel: false });
                    }
                } else {
                    wx.hideLoading();
                    wx.showModal({ content: '服务器报错，请重试！', showCancel: false });
                }
            }
        })
    })
}

const getNewToken = () => {
    return new Promise((resolve, reject) => {
        wx.login({
            success(res) {
                wx.request({
                    "url": baseUrl + "/api/saleUserLogin/getSessionKey",
                    "method": 'GET',
                    "data":{
                        code:res.code
                    },
                    "header":{
                        'content-type': 'application/x-www-form-urlencoded',
                        'appCode': appCode,
                        'version': version
                    },
                    success(res) {
                        let r = res.data;
                        // 将所有存储到观察者数组中的请求重新执行。
                        if (r.code == 200) {
                            wx.setStorageSync('openid', r.data.openid);
                            wx.setStorageSync('session_key', r.data.session_key);
                            resolve(res);
                        }
                        else{
                            wx.showModal({ content: r.msg, showCancel: false });
                        }
                    }
                })
            },
            fail(err) {
                reject()
                console.error('wx login fail', err);
            }
        });
    })
}

module.exports = {
    request,
    upload,
    getNewToken
}